<template>
<div class="form-group" >
  <input v-if="tag!=='textarea'"  @blur='InputRuleshandle' :class="{'is-invalid': InputRules.error}"  type="email" :value="InputRules.val" v-bind='$attrs' @input="updateValue" class="form-control"  aria-describedby="emailHelp" >
<textarea v-else
@blur='InputRuleshandle' :class="{'is-invalid': InputRules.error}"  type="email" :value="InputRules.val" v-bind='$attrs' @input="updateValue" class="form-control"  aria-describedby="emailHelp" >

</textarea>
  <span v-if='InputRules.error' class="invalid-feedback">{{InputRules.message}}</span>

  </div>

</template>

<script lang='ts'>
import { defineComponent, PropType, reactive, onMounted, watch } from 'vue'
import { emitter } from '../components/ValidateForm.vue'
export interface EmailRules {
    type: 'required' | 'emailreg' | 'custom';
    message: string;

}
export type TagType = 'input' | 'textarea'
export default defineComponent({
  name: 'ValidateInput',
  props: {
    rules: {
      type: Array as PropType <EmailRules[]>,
      require: true
    },
    modelValue: {
      type: String,
      required: false
    },
    tag: {
      type: String as PropType<TagType>,
      default: 'input'
    }
  },
  inheritAttrs: false,
  setup (props, context) {
    const emailReg = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
    const InputRules = reactive({
      val: props.modelValue || '',
      message: '',
      error: false
    })
    watch(() => props.modelValue, (newValue) => {
      console.log(newValue)

      InputRules.val = newValue || ''
    })
    const updateValue = (e: KeyboardEvent) => {
      const targetValue = (e.target as HTMLInputElement).value
      InputRules.val = targetValue
      context.emit('update:modelValue', targetValue)
    }
    const InputRuleshandle = () => {
      if (props.rules) {
        const allpased = props.rules.every(rule => {
          let passed = true
          InputRules.message = rule.message
          switch (rule.type) {
            case 'required':
              passed = (InputRules.val.trim() !== '')
              break
            case 'emailreg':
              passed = emailReg.test(InputRules.val)
              break
            default:
              break
          }
          return passed
        })
        InputRules.error = !allpased
        return allpased// 这里注意
      }
      return true // 没有规则，拿那就直接返回一个true
    }

    emitter.emit('item', InputRuleshandle)// 就是去发射这个验证函数

    return {
      InputRules,
      InputRuleshandle,
      updateValue
    }
  }
})

</script>

<style>

</style>
